package com.huikeportal.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.huikeportal.controller.common.Log;
import com.huikeportal.controller.common.MD5Util;
import com.huikeportal.controller.common.MessageManager;
import com.huikeportal.controller.common.Tools;
import com.huikeportal.dao.AspnetMembershipMapper;
import com.huikeportal.dao.AspnetUsersInRolesMapper;
import com.huikeportal.dao.AspnetUsersMapper;
import com.huikeportal.dao.LoginMapper;
import com.huikeportal.dao.PrivilegeUserDataMapper;
import com.huikeportal.dao.PrivilegeUsersBDDetailMapper;
import com.huikeportal.dao.PrivilegeUsersSiteMapper;
import com.huikeportal.dao.RoleMapper;
import com.huikeportal.dao.SelectSiteMapper;
import com.huikeportal.dao.UserManagerMapper;
import com.huikeportal.model.AspnetMembership;
import com.huikeportal.model.AspnetUsers;
import com.huikeportal.model.AspnetUsersInRoles;
import com.huikeportal.model.DataTypeIndex;
import com.huikeportal.model.MessageCommon;
import com.huikeportal.model.PrivilegeUserData;
import com.huikeportal.model.PrivilegeUsersBDDetail;
import com.huikeportal.model.PrivilegeUsersSite;
import com.huikeportal.model.SiteAllInfo;
import com.huikeportal.model.SiteCommon;
import com.huikeportal.model.TreeHtml;
import com.huikeportal.model.UserInfo;
import com.huikeportal.model.UserManagerInfo;
import com.huikeportal.model.WordBook;
import com.huikeportal.model.common.PageDataVo;
import com.huikeportal.model.common.SqlParameter;
import com.huikeportal.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private LoginMapper loginMapper;

	@Autowired
	private UserManagerMapper userManagerMapper;

	@Autowired
	private AspnetUsersMapper aspnetUsersMapper;

	@Autowired
	private SelectSiteMapper selectSiteMapper;

	@Autowired
	private AspnetMembershipMapper aspnetMembershipMapper;

	@Autowired
	private AspnetUsersInRolesMapper aspnetUsersInRolesMapper;

	@Autowired
	private PrivilegeUsersSiteMapper privilegeUsersSiteMapper;

	@Autowired
	private PrivilegeUserDataMapper privilegeUserDataMapper;

	@Autowired
	private PrivilegeUsersBDDetailMapper privilegeUsersBDDetailMapper;

	/**
	 * 用户管理分页
	 */
	public PageDataVo getUserList(PageDataVo pageDataVo) throws Exception {
		int maxTotal = userManagerMapper.queryUserTotal(pageDataVo);
		List<UserManagerInfo> userList = userManagerMapper
				.queryUserList(pageDataVo);
		// 循环用户列表，查询用户的场所权限信息
		for (int j = 0; j < userList.size(); j++) {
			List<SiteAllInfo> userSiteList = userManagerMapper
					.querySiteInfoByUser(userList.get(j).getUserId());
			List<SiteAllInfo> jtList = new ArrayList<SiteAllInfo>();
			List<SiteAllInfo> dyList = new ArrayList<SiteAllInfo>();
			List<SiteAllInfo> gcList = new ArrayList<SiteAllInfo>();
			List<SiteAllInfo> dpList = new ArrayList<SiteAllInfo>();
			for (int i = 0; i < userSiteList.size(); i++) {
				if (!"".equals(userSiteList.get(i))
						&& userSiteList.get(i) != null
						&& !"".equals(userSiteList.get(i).getSiteid())) {
					if (userSiteList.get(i).getType() == 100) {
						jtList.add(userSiteList.get(i));
					} else if (userSiteList.get(i).getType() == 200) {
						dyList.add(userSiteList.get(i));
					} else if (userSiteList.get(i).getType() == 300) {
						gcList.add(userSiteList.get(i));
					} else if (userSiteList.get(i).getType() == 600) {
						dpList.add(userSiteList.get(i));
					}
				}
			}
			String siteNameString = "";
			if (jtList.size() > 0) {
				siteNameString += "集团:";
				for (int k = 0; k < jtList.size(); k++) {
					siteNameString += jtList.get(k).getSitename() + ",";
				}
				siteNameString = siteNameString.substring(0, siteNameString
						.length() - 1);
				siteNameString += "\n";
			}
			if (dyList.size() > 0) {
				siteNameString += "地域:";
				for (int k = 0; k < dyList.size(); k++) {
					siteNameString += dyList.get(k).getSitename() + ",";
				}
				siteNameString = siteNameString.substring(0, siteNameString
						.length() - 1);
				siteNameString += "\n";
			}
			if (gcList.size() > 0) {
				siteNameString += "广场:";
				for (int k = 0; k < gcList.size(); k++) {
					siteNameString += gcList.get(k).getSitename() + ",";
				}
				siteNameString = siteNameString.substring(0, siteNameString
						.length() - 1);
				siteNameString += "\n";
			}
			if (dpList.size() > 0) {
				siteNameString += "店铺:";
				for (int k = 0; k < dpList.size(); k++) {
					siteNameString += dpList.get(k).getSitename() + ",";
				}
				siteNameString = siteNameString.substring(0, siteNameString
						.length() - 1);
				siteNameString += "\n";
			}
			userList.get(j).setPlacePermission(siteNameString);
		}
		pageDataVo.setMaxRow(maxTotal);
		pageDataVo.setMaxPage((maxTotal + pageDataVo.getPageSize() - 1)
				/ pageDataVo.getPageSize());
		pageDataVo.setPageResult(userList);
		return pageDataVo;
	}

	/**
	 * 查询当前登录用户所有下属角色
	 */
	public List<TreeHtml> getUserRoleCombo(UserInfo userInfo) throws Exception {
		userInfo = loginMapper.getUserByName(userInfo);
		List<TreeHtml> roleList = roleMapper.getRoleById(userInfo);
		// size = roleList.size();
		// roleList = getFloor(roleList);
		// for (int i = 0; i < roleList.size(); i++) {
		// roleList.get(i).setRoleName(
		// space(roleList.get(i).getFloorNum())
		// + roleList.get(i).getRoleName());
		// }
		return roleList;
	}

	/**
	 * 查询所有的用户状态信息
	 */
	public List<WordBook> getUserStatusCombo(String sysLang) throws Exception {
		SqlParameter sql = new SqlParameter();
		sql.setString("hkcloud_user_status");
		sql.setSysLang(sysLang);
		return roleMapper.getButtonInfo(sql);
	}

	/**
	 * 查询数据权限复选框列表
	 */
	public List<WordBook> getDataPermission(SqlParameter sql) throws Exception {
		return userManagerMapper.queryDataPermission(sql);
	}

	/**
	 * 新增用户
	 */
	public MessageCommon addUser(UserManagerInfo userManagerInfo)
			throws Exception {
		// 插入aspnet_Users表
		AspnetUsers aspnetUsers = new AspnetUsers();
		aspnetUsers.setApplicationid(MessageManager.getMsg("application"));
		aspnetUsers.setUsername(userManagerInfo.getUserName().trim());
		aspnetUsers.setLoweredusername(userManagerInfo.getUserName().trim());
		aspnetUsers.setIsanonymous(false);// 是否匿名，默认为否
		aspnetUsers.setUsertype(2);// 是否收费，默认为2（免费）,现在用不到
		aspnetUsers.setMobilealias(null);// 不知道什么字段，默认空
		aspnetUsers.setCreateUserName(userManagerInfo.getCreateUserId().trim());
		aspnetUsers.setSource(Integer.parseInt(MessageManager
				.getMsg("insertSource")));
		aspnetUsers.setLastactivitydate(new Date());
		// 用户登录权限
		if ("on".equals(userManagerInfo.getIsPcLogin())) {
			aspnetUsers.setPcenable(1);
		} else {
			aspnetUsers.setPcenable(0);
		}
		if ("on".equals(userManagerInfo.getIsMobLogin())) {
			aspnetUsers.setMobileenable(1);
		} else {
			aspnetUsers.setMobileenable(0);
		}
		if ("on".equals(userManagerInfo.getIsSendMessage())) {
			aspnetUsers.setSendmessage(1);
		} else {
			aspnetUsers.setSendmessage(0);
		}
		// 2016年2月26日09:51:30新增运维用户的用户类型跟随创建者
		// 取当前客户的上级客户
		UserInfo topInfo = new UserInfo();
		topInfo.setUserName(userManagerInfo.getCreateUserId().trim());
		topInfo = loginMapper.getUserByName(topInfo);
		// 如果创建者是运维账号，则创建的该账号也是运维账号
		if ("2".equals(topInfo.getUserType())) {
			aspnetUsers.setCustomerType("2");
		}
		// 2016年2月26日09:51:44新增 --end
		aspnetUsersMapper.insertSelective(aspnetUsers);
		// 插入aspnet_Membership表
		AspnetMembership aspnetMembership = new AspnetMembership();
		aspnetMembership.setApplicationid(MessageManager.getMsg("application"));
		aspnetMembership.setUserid(aspnetUsers.getUserid());
		aspnetMembership.setPassword(MD5Util.GetMD5Code("123456"));
		aspnetMembership.setPasswordformat(0);// 现在不用了
		aspnetMembership.setPasswordsalt("0");// 现在不用了
		aspnetMembership.setEmail(userManagerInfo.getEmail().trim());
		aspnetMembership.setLoweredemail(userManagerInfo.getEmail().trim()
				.toLowerCase());
		aspnetMembership.setIsapproved(false);// 现在不用了
		aspnetMembership.setIslockedout(false);// 是否锁定，默认不锁定
		aspnetMembership.setCreatedate(new Date());
		aspnetMembership.setLastlogindate(new Date());
		aspnetMembership.setLastpasswordchangeddate(new Date());
		aspnetMembership.setLastlockoutdate(new Date());// 上次锁定时间
		aspnetMembership.setFailedpasswordattemptcount(0);// 现在不用了
		aspnetMembership.setFailedpasswordattemptwindowstart(new Date());// 现在不用了
		aspnetMembership.setFailedpasswordanswerattemptcount(0);// 现在不用了
		aspnetMembership.setFailedpasswordanswerattemptwindowstart(new Date());// 现在不用了
		aspnetMembership.setPhoneno(userManagerInfo.getTel().trim());
		aspnetMembership.setMobilepin(userManagerInfo.getPhone().trim());
		aspnetMembership.setComment(userManagerInfo.getNote().trim());
		aspnetMembership.setRealname(userManagerInfo.getRealName().trim());
		aspnetMembership.setAddress(null);// 暂时没用到
		aspnetMembership.setSource(Integer.parseInt(MessageManager
				.getMsg("insertSource")));
		aspnetMembership.setCustomerStatus("0");// 未开通
		aspnetMembershipMapper.insertSelective(aspnetMembership);
		// 插入aspnet_UsersInRoles表
		AspnetUsersInRoles aspnetUsersInRoles = new AspnetUsersInRoles();
		aspnetUsersInRoles.setUserid(aspnetUsers.getUserid());
		aspnetUsersInRoles.setRoleid(userManagerInfo.getRoleId());
		aspnetUsersInRoles.setCreatetime(new Date());
		aspnetUsersInRoles.setSource(Integer.parseInt(MessageManager
				.getMsg("insertSource")));
		aspnetUsersInRolesMapper.insertSelective(aspnetUsersInRoles);
		// 插入数据权限、报告权限等表
		// 获取数据权限列表
		String[] dataList = userManagerInfo.getDataList().split(",");
		// 插入Privilege_UserData表
		for (int i = 0; i < dataList.length; i++) {
			PrivilegeUserData privilegeUserData = new PrivilegeUserData();
			privilegeUserData.setUserid(aspnetUsers.getUserid());
			privilegeUserData.setDatatype(Integer.parseInt(dataList[i]));
			privilegeUserDataMapper.insertSelective(privilegeUserData);
		}
		// 根据创建者获取当前登录用户的广场权限
		List<SiteAllInfo> allGcList = userManagerMapper
				.getGcListByUserName(userManagerInfo.getCreateUserId());
		// 分割广场和店铺权限
		String gcDp = userManagerInfo.getGcSiteId();
		List<SiteAllInfo> gc = new ArrayList<SiteAllInfo>();
		List<SiteAllInfo> dp = new ArrayList<SiteAllInfo>();
		List<SiteAllInfo> gcDpList = userManagerMapper.getSiteByString(gcDp);
		for (int i = 0; i < gcDpList.size(); i++) {
			if (gcDpList.get(i).getType() == 300) {
				gc.add(gcDpList.get(i));
			} else if (gcDpList.get(i).getType() == 600) {
				dp.add(gcDpList.get(i));
			}
		}
		gc = filterGcList(allGcList, gc);
		userManagerInfo.setGcSiteId(Tools.pinjieId(gc));
		userManagerInfo.setDpSiteId(Tools.pinjieId(dp));
		// 新增用户场所权限
		PrivilegeUsersBDDetail privilegeUsersBDDetail = new PrivilegeUsersBDDetail();
		privilegeUsersBDDetail.setUserId(aspnetUsers.getUserid());
		if (!"".equals(userManagerInfo.getJtSiteId())) {
			privilegeUsersBDDetail.setCheck100(userManagerInfo.getJtSiteId());
		}
		if (!"".equals(userManagerInfo.getJinjituan())) {
			privilegeUsersBDDetail.setOnly100("1");
		} else {
			privilegeUsersBDDetail.setOnly100("0");
		}
		if (!"".equals(userManagerInfo.getDySiteId())) {
			privilegeUsersBDDetail.setCheck200(userManagerInfo.getDySiteId());
		}
		if (!"".equals(userManagerInfo.getJindiyu())) {
			privilegeUsersBDDetail.setOnly200("1");
		} else {
			privilegeUsersBDDetail.setOnly200("0");
		}
		if (!"".equals(userManagerInfo.getGcSiteId())) {
			privilegeUsersBDDetail.setSite300(userManagerInfo.getGcSiteId());
		}
		if (!"".equals(userManagerInfo.getDpSiteId())) {
			privilegeUsersBDDetail.setSite600(userManagerInfo.getDpSiteId());
		}
		privilegeUsersBDDetail.setCreateTime(new Date());
		privilegeUsersBDDetailMapper.insertSelective(privilegeUsersBDDetail);
		// 获取用户所有场所权限
		String[] siteList = getUserPerList(userManagerInfo).split(",");
		// 循环插入Privilege_UsersSite表
		for (int i = 0; i < siteList.length; i++) {
			PrivilegeUsersSite privilegeUsersSite = new PrivilegeUsersSite();
			privilegeUsersSite.setUserid(aspnetUsers.getUserid());
			privilegeUsersSite.setSitekey(siteList[i]);
			privilegeUsersSite.setGroupid(0);// 没有用到，默认为0
			privilegeUsersSite.setCreatetime(new Date());
			privilegeUsersSite.setModifytime(new Date());
			privilegeUsersSite.setSource(Integer.parseInt(MessageManager
					.getMsg("insertSource")));
			privilegeUsersSiteMapper.insertSelective(privilegeUsersSite);
		}
		// // 如果用户有场所权限
		// if (userManagerInfo.getSiteList() != null) {
		// // 循环插入Privilege_UsersSite表
		// String[] siteList = userManagerInfo.getSiteList().split(",");
		// for (int i = 0; i < siteList.length; i++) {
		// PrivilegeUsersSite privilegeUsersSite = new PrivilegeUsersSite();
		// privilegeUsersSite.setUserid(aspnetUsers.getUserid());
		// privilegeUsersSite.setSitekey(siteList[i]);
		// privilegeUsersSite.setGroupid(0);// 没有用到，默认为0
		// privilegeUsersSite.setCreatetime(new Date());
		// privilegeUsersSite.setModifytime(new Date());
		// privilegeUsersSite.setSource(Integer.parseInt(MessageManager
		// .getMsg("insertSource")));
		// privilegeUsersSiteMapper.insertSelective(privilegeUsersSite);
		// }
		// }
		MessageCommon message = new MessageCommon();
		message.setFlag(true);
		message.setMessage("新增用户成功！");
		// 插入日志表
		Log log = Log.getLogger();
		log.logger.info("新增用户:" + aspnetUsers.getUsername());
		return message;
	}

	/**
	 * 过滤广场权限(不能大于当前创建者的权限)
	 * 
	 * @param allGcList
	 * @param gcList
	 * @return
	 */
	private List<SiteAllInfo> filterGcList(List<SiteAllInfo> allGcList,
			List<SiteAllInfo> gcList) {
		List<SiteAllInfo> resultList = new ArrayList<SiteAllInfo>();
		if (allGcList.size() == 0) {
			return resultList;
		} else {
			for (int i = 0; i < gcList.size(); i++) {
				boolean flag = false;
				for (int j = 0; j < allGcList.size(); j++) {
					if (gcList.get(i).getSiteid().equals(
							allGcList.get(j).getSiteid())) {
						flag = true;
						break;
					}
				}
				if (flag) {
					resultList.add(gcList.get(i));
				}
			}
		}
		return resultList;
	}

	/**
	 * 获取需要新增的用户场所权限信息
	 * 
	 * @param userManagerInfo
	 * @return
	 * @throws Exception
	 */
	private String getUserPerList(UserManagerInfo user) throws Exception {
		String jtId = user.getJtSiteId();
		String jinjituan = user.getJinjituan();
		String dyId = user.getDySiteId();
		String jindiyu = user.getJindiyu();
		String gcId = user.getGcSiteId();
		String dpId = user.getDpSiteId();
		List<SiteAllInfo> jtList = new ArrayList<SiteAllInfo>();
		List<SiteAllInfo> jtGcList = new ArrayList<SiteAllInfo>();
		List<SiteAllInfo> dyList = new ArrayList<SiteAllInfo>();
		List<SiteAllInfo> dyGcList = new ArrayList<SiteAllInfo>();
		List<SiteAllInfo> gcList = new ArrayList<SiteAllInfo>();
		List<SiteAllInfo> dpList = new ArrayList<SiteAllInfo>();
		// 如果选中了集团
		if (!"".equals(jtId)) {
			// 将集团加入集团结果集
			jtList = userManagerMapper.getSiteByString(jtId);
			// 如果没有选中仅集团
			if ("".equals(jinjituan)) {
				// 将该集团下的广场加入集团-广场结果集
				SqlParameter sql = new SqlParameter();
				sql.setString(jtId);
				sql.setStringChar("300");
				jtGcList = userManagerMapper.selectParent100(sql);
				// 此时将所选的地域、广场、店铺清空(去重)
				dyId = "";
				gcId = "";
				dpId = "";
			}
		}
		// 如果选中了地域
		if (!"".equals(dyId)) {
			// 将地域加入地域结果集
			dyList = userManagerMapper.getSiteByString(dyId);
			// 如果没有选中仅地域
			if ("".equals(jindiyu)) {
				// 将地域下的广场加入地域-广场结果集
				SqlParameter sql = new SqlParameter();
				sql.setString(dyId);
				sql.setStringChar("300");
				dyGcList = userManagerMapper.selectParent200(sql);
			}
		}
		// 如果选中了广场
		if (!"".equals(gcId)) {
			// 如果选中了区域下的广场,去重
			if (dyGcList.size() > 0) {
				String newGcId = "";
				String[] gc = gcId.split(",");
				for (int i = 0; i < gc.length; i++) {
					boolean flag = false;
					for (int j = 0; j < dyGcList.size(); j++) {
						if (dyGcList.get(j).getSiteid().equals(gc[i])) {
							flag = true;
							break;
						}
					}
					if (!flag) {
						newGcId += gc[i] + ",";
					}
				}
				if (!"".equals(newGcId)) {
					newGcId = newGcId.substring(0, newGcId.length() - 1);
				}
				gcId = newGcId;
			}
			gcList = userManagerMapper.getSiteByString(gcId);
		}
		// 如果选中了店铺
		if (!"".equals(dpId)) {
			// 去重
			String newDpId = "";
			String[] dp = dpId.split(",");
			for (int i = 0; i < dp.length; i++) {
				boolean flag = false;
				// 根据店铺查询所属广场
				SiteCommon dpSite = selectSiteMapper.querySiteInfo(dp[i]);
				if (!"".equals(gcId)) {
					// 如果该广场已经选择
					if (gcId.indexOf(dpSite.getParent300()) != -1) {
						flag = true;
					}
				}
				// 如果该广场位于已选择的地域下
				if (dyGcList.size() > 0) {
					for (int j = 0; j < dyGcList.size(); j++) {
						if (dyGcList.get(j).getSiteid().equals(
								dpSite.getParent300())) {
							flag = true;
							break;
						}
					}
				}
				if (!flag) {
					newDpId += dp[i] + ",";
				}
			}
			if (!"".equals(newDpId)) {
				newDpId = newDpId.substring(0, newDpId.length() - 1);
			}
			dpId = newDpId;
			dpList = userManagerMapper.getSiteByString(dpId);
		}
		String resultString = "";
		if (jtList.size() != 0) {
			resultString += Tools.pinjieId(jtList) + ",";
		}
		if (jtGcList.size() != 0) {
			resultString += Tools.pinjieId(jtGcList) + ",";
		}
		if (dyList.size() != 0) {
			resultString += Tools.pinjieId(dyList) + ",";
		}
		if (dyGcList.size() != 0) {
			resultString += Tools.pinjieId(dyGcList) + ",";
		}
		if (gcList.size() != 0) {
			resultString += Tools.pinjieId(gcList) + ",";
		}
		if (dpList.size() != 0) {
			resultString += Tools.pinjieId(dpList) + ",";
		}
		resultString = resultString.substring(0, resultString.length() - 1);
		return resultString;
	}

	/**
	 * 用户编辑初始化
	 */
	public UserManagerInfo getUserById(UserManagerInfo userManagerInfo)
			throws Exception {
		userManagerInfo = userManagerMapper.getCustomById(userManagerInfo
				.getUserId());
		// 拼接用户数据权限
		List<String> dataList = userManagerMapper
				.getDataPerById(userManagerInfo.getUserId());
		String dataString = "";
		for (int i = 0; i < dataList.size(); i++) {
			dataString += dataList.get(i) + ",";
		}
		if (!"".equals(dataString)) {
			dataString = dataString.substring(0, dataString.length() - 1);
		}
		userManagerInfo.setDataList(dataString);
		// 获取用户场所权限详情
		PrivilegeUsersBDDetail siteDetail = userManagerMapper
				.querySiteDetailByUser(userManagerInfo.getUserId());
		userManagerInfo.setJtSiteId(siteDetail.getCheck100());
		userManagerInfo.setJinjituan(siteDetail.getOnly100());
		userManagerInfo.setDySiteId(siteDetail.getCheck200());
		userManagerInfo.setJindiyu(siteDetail.getOnly200());
		userManagerInfo.setGcSiteId(siteDetail.getSite300());
		userManagerInfo.setDpSiteId(siteDetail.getSite600());
		return userManagerInfo;
	}

	/**
	 * 编辑用户
	 */
	public MessageCommon editUser(UserManagerInfo userManagerInfo)
			throws Exception {
		// 更新aspnet_Users表
		AspnetUsers aspnetUsers = new AspnetUsers();
		aspnetUsers.setPcenable(0);
		aspnetUsers.setMobileenable(0);
		aspnetUsers.setSendmessage(0);
		if ("on".equals(userManagerInfo.getIsPcLogin())) {
			aspnetUsers.setPcenable(1);
		}
		if ("on".equals(userManagerInfo.getIsMobLogin())) {
			aspnetUsers.setMobileenable(1);
		}
		if ("on".equals(userManagerInfo.getIsSendMessage())) {
			aspnetUsers.setSendmessage(1);
		}
		aspnetUsers.setUserid(userManagerInfo.getUserId());
		aspnetUsersMapper.updateByPrimaryKeySelective(aspnetUsers);
		// 更新aspnet_Membership表
		AspnetMembership aspnetMembership = new AspnetMembership();
		aspnetMembership.setUserid(userManagerInfo.getUserId());
		aspnetMembership.setMobilepin(userManagerInfo.getPhone());
		aspnetMembership.setEmail(userManagerInfo.getEmail());
		aspnetMembership.setLoweredemail(userManagerInfo.getEmail());
		aspnetMembership.setComment(userManagerInfo.getNote());
		aspnetMembership.setPhoneno(userManagerInfo.getTel());
		aspnetMembership.setRealname(userManagerInfo.getRealName());
		aspnetMembership.setModifytime(new Date());
		aspnetMembershipMapper.updateByPrimaryKeySelective(aspnetMembership);
		// 更新aspnet_UsersInRoles表
		AspnetUsersInRoles aspnetUsersInRoles = new AspnetUsersInRoles();
		aspnetUsersInRoles.setUserid(userManagerInfo.getUserId());
		aspnetUsersInRoles.setRoleid(userManagerInfo.getRoleId());
		aspnetUsersInRoles.setUpdatetime(new Date());
		userManagerMapper.updateUserRole(aspnetUsersInRoles);
		// 根据创建者获取当前登录用户的广场权限
		List<SiteAllInfo> allGcList = userManagerMapper
				.getGcListByUserName(userManagerInfo.getCreateUserId());
		// 分割广场和店铺权限
		String gcDp = userManagerInfo.getGcSiteId();
		List<SiteAllInfo> gc = new ArrayList<SiteAllInfo>();
		List<SiteAllInfo> dp = new ArrayList<SiteAllInfo>();
		List<SiteAllInfo> gcDpList = userManagerMapper.getSiteByString(gcDp);
		for (int i = 0; i < gcDpList.size(); i++) {
			if (gcDpList.get(i).getType() == 300) {
				gc.add(gcDpList.get(i));
			} else if (gcDpList.get(i).getType() == 600) {
				dp.add(gcDpList.get(i));
			}
		}
		gc = filterGcList(allGcList, gc);
		userManagerInfo.setGcSiteId(Tools.pinjieId(gc));
		userManagerInfo.setDpSiteId(Tools.pinjieId(dp));
		// 更新用户场所详情表
		PrivilegeUsersBDDetail privilegeUsersBDDetail = new PrivilegeUsersBDDetail();
		privilegeUsersBDDetail.setUserId(aspnetUsers.getUserid());
		privilegeUsersBDDetail.setCheck100(userManagerInfo.getJtSiteId());
		if (!"".equals(userManagerInfo.getJinjituan())) {
			privilegeUsersBDDetail.setOnly100("1");
		} else {
			privilegeUsersBDDetail.setOnly100("0");
		}
		privilegeUsersBDDetail.setCheck200(userManagerInfo.getDySiteId());
		if (!"".equals(userManagerInfo.getJindiyu())) {
			privilegeUsersBDDetail.setOnly200("1");
		} else {
			privilegeUsersBDDetail.setOnly200("0");
		}
		privilegeUsersBDDetail.setSite300(userManagerInfo.getGcSiteId());
		privilegeUsersBDDetail.setSite600(userManagerInfo.getDpSiteId());
		privilegeUsersBDDetail.setUpdateTime(new Date());
		privilegeUsersBDDetailMapper
				.updateByPrimaryKeySelective(privilegeUsersBDDetail);
		// 删除Privilege_UsersSite表
		userManagerMapper.deleteUserSite(userManagerInfo.getUserId());
		// 循环插入Privilege_UsersSite表
		String[] siteList = getUserPerList(userManagerInfo).split(",");
		for (int i = 0; i < siteList.length; i++) {
			PrivilegeUsersSite privilegeUsersSite = new PrivilegeUsersSite();
			privilegeUsersSite.setUserid(userManagerInfo.getUserId());
			privilegeUsersSite.setSitekey(siteList[i]);
			privilegeUsersSite.setGroupid(0);
			privilegeUsersSite.setCreatetime(new Date());
			privilegeUsersSite.setModifytime(new Date());
			privilegeUsersSite.setSource(Integer.parseInt(MessageManager
					.getMsg("insertSource")));
			privilegeUsersSiteMapper.insertSelective(privilegeUsersSite);
		}
		// 删除Privilege_UserData表
		userManagerMapper.deleteUserData(userManagerInfo.getUserId());
		// 循环插入Privilege_UserData表
		String[] dataList = userManagerInfo.getDataList().split(",");
		for (int i = 0; i < dataList.length; i++) {
			PrivilegeUserData privilegeUserData = new PrivilegeUserData();
			privilegeUserData.setUserid(userManagerInfo.getUserId());
			privilegeUserData.setDatatype(Integer.parseInt(dataList[i]));
			privilegeUserData.setSource(Integer.parseInt(MessageManager
					.getMsg("insertSource")));
			privilegeUserDataMapper.insertSelective(privilegeUserData);
		}
		// // 删除Privilege_UsersBD表
		// userManagerMapper.deleteUserReport(userManagerInfo.getUserId());
		// // 循环插入Privilege_UsersBD表
		// String[] reportList = userManagerInfo.getReportList().split(",");
		// for (int i = 0; i < reportList.length; i++) {
		// PrivilegeUsersBDKey privilegeUsersBD = new PrivilegeUsersBDKey();
		// privilegeUsersBD.setUserid(userManagerInfo.getUserId());
		// privilegeUsersBD.setSiteid(reportList[i]);
		// privilegeUsersBDMapper.insertSelective(privilegeUsersBD);
		// }
		// 插入日志表
		MessageCommon messageCommon = new MessageCommon();
		messageCommon.setFlag(true);
		messageCommon.setMessage("编辑用户成功！");
		return messageCommon;
	}

	/**
	 * 删除、更改用户状态、密码重置
	 */
	public MessageCommon updateUser(UserManagerInfo userManagerInfo)
			throws Exception {
		AspnetMembership aspnetMembership = new AspnetMembership();
		aspnetMembership.setUserid(userManagerInfo.getUserId());
		if (!"-1".equals(userManagerInfo.getUserStatusDes())) {
			aspnetMembership.setCustomerStatus(userManagerInfo
					.getUserStatusDes());
			if ("2".equals(userManagerInfo.getUserStatusDes())) {
				aspnetMembership.setIslockedout(true);
			}
			if ("1".equals(userManagerInfo.getUserStatusDes())) {
				aspnetMembership.setIslockedout(false);
			}
		}
		// 如果是密码重置
		else {
			aspnetMembership.setPassword(MD5Util.GetMD5Code("123456"));
		}
		aspnetMembership.setModifytime(new Date());
		aspnetMembershipMapper.updateByPrimaryKeySelective(aspnetMembership);
		MessageCommon messageCommon = new MessageCommon();
		messageCommon.setFlag(true);
		messageCommon.setMessage("更新用户状态成功！");
		return messageCommon;
	}

	/**
	 * 判断用户名是否存在
	 */
	public boolean selectUserExists(String userName) throws Exception {
		Integer count = userManagerMapper.selectUserExists(userName);
		if (count == 0) {
			return true;
		}
		return false;
	}

	/**
	 * 检查当前用户的最大创建数
	 */
	public boolean checkMaxAccount(UserInfo userInfo) throws Exception {
		userInfo = loginMapper.getUserByName(userInfo);
		// 取当前客户的最上级客户
		UserInfo user = getCreateId(userInfo);
		// 根据客户id查询当前客户下已经创建了的用户数
		Integer userCreatedNum = userManagerMapper.selectAccountNum(user
				.getUserCustomId());
		// 根据客户id查询当前客户的场所权限并计算可以能够创建的最大用户数
		Integer maxNum = 0;
		List<SiteAllInfo> siteList = userManagerMapper.querySiteInfoByUser(user
				.getUserId());
		// 如果用户的场所权限上级为广场
		if (siteList.get(0).getType() == 300) {
			maxNum = siteList.size()
					* Integer
							.parseInt(MessageManager.getMsg("gcMaxAccountNum"));
		}
		// 如果用户的场所权限上级为集团
		else if (siteList.get(0).getType() == 100) {
			String jtString = "";
			for (int i = 0; i < siteList.size(); i++) {
				jtString += siteList.get(i).getSiteid() + ",";
			}
			jtString = jtString.substring(0, jtString.length() - 1);
			SqlParameter sqlParameter = new SqlParameter();
			sqlParameter.setString(jtString);
			sqlParameter.setStringChar("300");
			List<SiteAllInfo> gcList = userManagerMapper
					.selectParent100(sqlParameter);
			// 最大创建数=集团数*10+广场数*20
			maxNum = gcList.size()
					* Integer
							.parseInt(MessageManager.getMsg("gcMaxAccountNum"))
					+ siteList.size()
					* Integer
							.parseInt(MessageManager.getMsg("jtMaxAccountNum"));
		}
		// 如果当前已经达到了最大值
		if (maxNum <= userCreatedNum) {
			return false;
		}
		return true;
	}

	// 获取当前用户的最上级用户
	private UserInfo getCreateId(UserInfo userInfo) throws Exception {
		if (userInfo != null && userInfo.getCreateUserId() != null) {
			UserInfo usInfo = new UserInfo();
			usInfo.setUserName(userInfo.getCreateUserId());
			usInfo = loginMapper.getUserByName(usInfo);
			return getCreateId(usInfo);
		}
		return userInfo;
	}

	/**
	 * 根据场所id字符串查询所有场所信息
	 */
	public List<SiteAllInfo> getSiteByString(String string) throws Exception {
		return userManagerMapper.getSiteByString(string);
	}

	// 获取用户指标权限&对应数据类型
	public Map<String, Object> selectUserDateType(String string)
			throws Exception {
		List<DataTypeIndex> indexList = userManagerMapper
				.selectUserDateType(string);
		// 单独拧出数据类型
		List<DataTypeIndex> dataTypeList = new ArrayList<DataTypeIndex>();
		for (int i = 0; i < indexList.size(); i++) {
			if (!isExits(indexList.get(i).getDataType(), dataTypeList)) {
				DataTypeIndex dataTypeIndex = new DataTypeIndex();
				dataTypeIndex.setDataType(indexList.get(i).getDataType());
				dataTypeIndex.setDataTypeName(indexList.get(i)
						.getDataTypeName());
				dataTypeList.add(dataTypeIndex);
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("indexList", indexList);
		map.put("dataTypeList", dataTypeList);
		return map;
	}

	private boolean isExits(String dataType, List<DataTypeIndex> dataTypeList) {
		boolean flag = false;
		for (int i = 0; i < dataTypeList.size(); i++) {
			if (dataType.equals(dataTypeList.get(i).getDataType())) {
				flag = true;
				return flag;
			}
		}
		return flag;
	}

}
